//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 付启刚 on 15/12/15.
//  Copyright © 2015年 faq. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
class OAuthViewController: UIViewController {
    
    let webView=UIWebView()
    
    @objc private func close(){
        
    dismissViewControllerAnimated(true, completion: nil)
        
        }
    //添加一个默认账户
    @objc private func defaultAccount(){
        let JSString="document.getElementById('userId').value='414102337@qq.com',document.getElementById('passwd').value='f8848q2358,'"
        webView.stringByEvaluatingJavaScriptFromString(JSString)
    }
    override func loadView() {
            view = webView
            //设置代理方法
        webView.delegate=self
            
        }
    override func viewDidLoad(){
        super.viewDidLoad()
        loadOauthPage()
        setNavBar()
        }
    private func loadOauthPage(){
        let urlString="https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url=NSURL(string: urlString)
        //print("xxxxxx%s",urlString)
        webView.loadRequest(NSURLRequest(URL: url!))
        }
    //设置导航条
        private func setNavBar(){
        self.navigationItem.leftBarButtonItem=UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
            self.navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
        }
    }
  //extension 是相关的代码更加模块快  易与阅读和维护
    extension OAuthViewController:UIWebViewDelegate{
        func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        }
        @objc func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        }
        func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        //需要根据请求的url 去屏蔽不希望加载的页面
            guard let urlString=request.URL?.absoluteString else{
            return false
            }
            //print(urlString)
            if urlString.hasPrefix("https://api.weibo.com/"){
                //请求成功回调的页面
               // print("======%s",urlString)
            return true
            }
            if !urlString.hasPrefix("http://www.baidu.com"){
                //一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
            return false
            }
            //走到这一定是成功的回调
            //解析字符串获取code码
            // query 获取到url中 参数部分 键值
            let query=request.URL?.query
            if let q=query{
            //截取code
                let codeStr="code="
                let code=q.substringFromIndex(codeStr.endIndex)
                print("----------")
                print(code)
                //加载用户token
                loadAccessToken(code)
                
            }
            return false
        }
        // MARK:加载用户token(请求标识)
        private func loadAccessToken(code: String) {
            
            UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
                if isSuccess {
                    print("登陆成功")
                    //动画结束的时候 发出 页面切换的通知
                    //通知是同步的还是异步的?
                    //通知是同步的
                    //这个方法是控制器dismiss掉 但是并不会立即被回收
                    //modla出来的页面 注意回收 需要手动close
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                        //等待 被modal出来的页面 彻底被回收是 再发出页面切换的通知
                        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVCNotification, object: "Welcome")
                        print("come here")
                    })
                } else {
                    print("登陆失败")
                }
            }
        }
}

        